package org.example.springbirthday.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.springbirthday.constants.Constants;
import org.example.springbirthday.model.Notice;
import org.example.springbirthday.model.Result;
import org.example.springbirthday.service.NoticeService;
import org.example.springbirthday.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/8/13
 * Time: 21:19
 */
@RestController
@RequestMapping("/notice")
@Slf4j
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    @RequestMapping("getNoticeByUserId")
    public Notice  getNoticeByUserId(Integer id) {
        log.info("根据用户id获取公告,接收到参数,id:{}", id);
        return noticeService.getNoticeById(id);
    }

    @RequestMapping("getNoticeList")
    public List<Notice> getNoticeList() {
        log.info("获取公告列表");
        return noticeService.getNoticeList();
    }

    @RequestMapping("/publish")
    public Result<String> publish(@RequestBody Notice notice, HttpServletRequest request) {
        if (!StringUtils.hasLength(notice.getTitle()) ||  !StringUtils.hasLength(notice.getContext())) {
            return Result.fail("标题或内容为空");
        }
        log.info("发布公告,notice:{}",notice);
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        log.info("发布公告,解析token:{}",token);
        Integer userId = JwtUtils.getIdByToken(token);
        log.info("发布公告,解析userId:{}",userId);
        try {
            Integer ret = noticeService.publish(notice, userId);
            if(ret == 1){
                return Result.success("公告发布成功");
            }
        }catch (Exception e){
            log.error("公告发布失败,e",e);
        }
        return Result.fail("公告发布失败");
    }

    @RequestMapping("/update")
    public Result<String> update(Notice notice){
        log.info("更新公告,notice:{}",notice);
        try {
            Integer ret = noticeService.update(notice);
            if(ret == 1){
                return Result.success("公告修改成功");
            }
        }catch (Exception e){
            log.error("公告修改失败,e",e);
        }
        return Result.fail("公告修改失败");
    }

    @RequestMapping("/delete")
    public Result<String> delete(Integer id){
        log.info("删除公告,id:{}",id);
        try{
            Integer ret = noticeService.delete(id);
            if(ret == 1){
                return Result.success("公告删除成功");
            }
        }catch (Exception e){
            log.error("公告删除失败,e",e);
        }
        return Result.fail("公告删除失败");
    }
}
